package fr

import (
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	faceid "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/faceid/v20180301"
	"log"
	"rlhs/config"
)

type livenessRecognition struct {
}

func NewLivenessRecognition() *livenessRecognition {
	return &livenessRecognition{}
}

func (*livenessRecognition) getCredential() *common.Credential {
	credential := common.NewCredential(
		config.Secrets.GetString("TencentCloudSecret.SecretId"),
		config.Secrets.GetString("TencentCloudSecret.SecretKey"),
	)
	return credential
}

func (lr *livenessRecognition) getClient() (client *faceid.Client, err error) {
	credential := lr.getCredential()
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = config.Confs.GetString("FaceIDConf.Endpoint")
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, err = faceid.NewClient(credential, "", cpf)
	return
}

func (lr *livenessRecognition) getRequest(input map[string]string) *faceid.LivenessRecognitionRequest {
	request := faceid.NewLivenessRecognitionRequest()
	request.IdCard = common.StringPtr(input["id_card"])
	request.Name = common.StringPtr(input["name"])
	request.VideoBase64 = common.StringPtr(input["video_base64"])
	request.VideoUrl = common.StringPtr(input["video_url"])
	request.ValidateData = common.StringPtr(input["validate_data"])
	request.LivenessType = common.StringPtr(input["liveness_type"])
	return request
}

func (lr *livenessRecognition) getResponse(res *faceid.LivenessRecognitionResponse) (string, error) {
	return res.ToJsonString(), nil
}

func (lr *livenessRecognition) Recognition(input map[string]string) (string, error) {
	client, _ := lr.getClient()
	request := lr.getRequest(input)
	response, err := client.LivenessRecognition(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		log.Printf("An API error has returned:%s", err)
		return "", err
	}
	return lr.getResponse(response)
}
